import router from './router'
import store from './store'
import {ElMessage} from "element-plus";

const whiteList = ['/login', '/register', '/401', '/404']
export const ROLE_MAP = new Map([
    [1, 'user'],
    [2, 'merchant'],
    [3, 'admin']
]);

router.beforeEach((to, from, next) => {
    // 未登录处理
    if (!store.state.userInfo) {
        if (to.path === '/') {
            next('/login')
        }
        if (whiteList.includes(to.path)) {
            next()
        } else {
            ElMessage.error('登录状态已失效')
            next(`/login?redirect=${to.path}`)
        }
        return
    }

    // 获取用户信息
    const userInfo = store.state.userInfo

    // 权限判断
    if (to.meta?.roles) {
        const hasRole = userInfo.roles.some(role => to.meta.roles.includes(role))
        if (!hasRole) {
            next('/401')
            return
        }
    }

    next()
})